<template>
  <div>
    <div>
      <FormPanel ref="formPanel" :list="formList" :cols="2" :labelWidth="110" :formType="type" :isSubmitBtn="false" @formChange="formChangeHandle" />
    </div>
    <div>
      <el-button size="small" type="primary" @click="pushTable()">计划明细生成</el-button>
    </div>
    <FilterTable
      ref="table"
      columnsRef="partAccessDesignTabsAddModel"
      :columns="columns"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="saveData"
    >
    </FilterTable>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog(1)">取 消</el-button>
      <el-button v-if="type !== 'show'" type="primary" @click="closeDialog(2)">{{ btnText }}</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { addPlan } from '@/api/parts/access/design';

export default {
  name: 'BrandModal',
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    this.BaseTable = null;
    return {
      formData: {},
      arr: [],
      formList: this.createFormList(),
      fetchParams: {},
      columns: this.createColumns()
    };
  },
  computed: {
    btnText() {
      return this.conf[this.type];
    }
  },
  created() {
    this.init();
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    init() {
      if (this.type === 'edit') {
        // 更新接口需要的记录 ID
        this.recordId = this.rowData.brandId;
        this.formList.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
        });
      }
    },
    saveData(row) {
      this.arr = [];
      if (row.length > 0) {
        for (let i = 0; i < row.length; i++) {
          this.arr.push(row[i]);
        }
      }
      console.log(this.arr);
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '盘点计划编码',
          fieldName: 'stockTakingNo',
          placeholder: '请输入...',
          rules: [{ required: true, message: '盘点计划编码不能为空', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '盘点计划名称',
          fieldName: 'stockTakingName',
          placeholder: '请输入...',
          rules: [{ required: true, message: '盘点计划名称不能为空', trigger: 'blur' }]
        },
        {
          type: 'RANGE_DATE',
          label: '计划周期',
          fieldName: 'planBegin|planEnd',
          placeholder: '请选择',
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '计划周期不能为空', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '计划类型',
          fieldName: 'planType',
          placeholder: '请选择...',
          itemList: [
            { value: 10451001, text: '仓库' },
            { value: 10451003, text: '盘点单号' }
          ],
          rules: [{ required: true, message: '计划类型', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '盘点周期',
          fieldName: 'stockTakingCycle',
          placeholder: '请选择...',
          itemList: [
            { value: 10451001, text: '日盘' },
            { value: 10451003, text: '月盘' }
          ],
          rules: [{ required: true, message: '盘点周期不能为空', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '提醒日为每周/每月第',
          fieldName: 'remindDate',
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '提醒日', trigger: 'change' }],
          unitRender: () => {
            return <span>天</span>;
          }
        },
        {
          type: 'SELECT',
          label: '盘点类型',
          fieldName: 'stockTakingType',
          placeholder: '请选择...',
          itemList: this.createDictList('1004'),
          itemList: [
            { value: 10451001, text: '全盘' },
            { value: 10451003, text: '动态盘点' }
          ],
          rules: [{ required: true, message: '更新日期不能为空', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '排序方式',
          fieldName: 'sortBy',
          placeholder: '请选择...',
          itemList: this.createDictList('1004'),
          itemList: [
            { value: 10451001, text: '仓库+库位' },
            { value: 10451003, text: '仓库+配件代码' },
            { value: 10451003, text: '仓库+配件名称' }
          ],
          rules: [{ required: true, message: '排序方式不能为空', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '每张盘点单配件个数',
          fieldName: 'count',
          placeholder: '1000',
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '每张盘点单配件个数不能为空', trigger: 'change' }]
        }
      ];
    },
    createColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 60,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deleteRow(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '时间范围',
          dataIndex: 'timeFrame',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '提醒日期',
          dataIndex: 'remindDate',
          sorter: true,
          filter: true,
          filterType: 'date'
        },
        {
          title: '选取仓库',
          dataIndex: 'wareHourse',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '仓库名称',
          dataIndex: 'wareHourseName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '排序方式',
          dataIndex: 'sortBy',
          sorter: true,
          filter: true,
          filterType: 'select'
        },
        {
          title: '入库开始日期',
          dataIndex: 'inStorageBegin',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '入库结束日期',
          dataIndex: 'inStorageEnd',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '出库开始日期',
          dataIndex: 'outStorageBegin',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '出库结束日期',
          dataIndex: 'outStorageEnd',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '每张盘点单配件个数',
          dataIndex: 'count',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '处理状态',
          dataIndex: 'handleStatus',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    formChangeHandle(val) {
      this.formData = val;
      console.log(val);
    },
    pushTable() {
      this.$refs.formPanel.SUBMIT_FORM();
      let arr = this.formData['planBegin|planEnd'];
      let remindDate = this.formData.remindDate;
      let sortBy = this.formData.sortBy;
      let handleStatus = this.formData.handleStatus;
      let count = this.formData.count;
      let start = new Date(arr[0]);
      let end = new Date(arr[1]);
      let curDate = start;
      let remDate = start;
      const DAYTIME = 24 * 60 * 60 * 1000;
      let a = start.getTime();
      let b = end.getTime();
      let str = this.dateToStr(start);
      let tableArr = [];
      let remindArr = [];
      let dayOfWeek = start.getDay();
      let dateStr = '';
      if (dayOfWeek != 7) {
        curDate = this.plusDays(start, 7 - dayOfWeek, DAYTIME);
        dateStr = `${str}至${this.dateToStr(curDate)}`;
        tableArr.push(dateStr);
        let remind = dayOfWeek + Number(remindDate - 1);
        remDate = remind >= 7 ? curDate : this.plusDays(start, remindDate - 1, DAYTIME);
        remindArr.push(this.dateToStr(remDate));
      }
      curDate = this.plusDays(curDate, 1, DAYTIME);
      while (a < b) {
        str = this.dateToStr(curDate);
        curDate = this.plusDays(curDate, remindDate - 1, DAYTIME);
        a = curDate.getTime();
        if (a < b) {
          remindArr.push(this.dateToStr(curDate));
          curDate = this.plusDays(curDate, 7 - remindDate, DAYTIME);
          a = curDate.getTime();
          curDate = a < b ? curDate : end;
          dateStr = `${str}至${this.dateToStr(curDate)}`;
          tableArr.push(dateStr);
        } else {
          remindArr.push(this.dateToStr(end));
          dateStr = `${str}至${this.dateToStr(end)}`;
          tableArr.push(dateStr);
        }
        curDate = this.plusDays(curDate, 1, DAYTIME);
        a = curDate.getTime();
      }
      let array = [];
      for (let i = 0; i < tableArr.length; i++) {
        let js = {
          timeFrame: tableArr[i],
          remindDate: remindArr[i],
          sortBy: sortBy,
          handleStatus: handleStatus,
          count: count
        };
        array.push(js);
      }
      this.BaseTable.EXECUTE_INSERT(array);
    },
    plusDays(date, num, rem) {
      return new Date(date.getTime() + rem * num);
    },
    dateToStr(date) {
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      if (month < 10) {
        month = `0${month}`;
      }
      if (day < 10) {
        day = `0${day}`;
      }
      return `${year}-${month}-${day}`;
    },
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      let data = Object.assign({}, this.formData, { dms_table2: this.arr });
      console.log(data);
      if (data !== null) {
        let res = {};
        res = await addPlan(data);
      }
    },
    closeDialog(type) {
      if (type == 1) {
        this.$emit('close', false);
      } else {
        this.$confirm('是否确定保存？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            console.log('qweqwer');
            this.$refs.formPanel.SUBMIT_FORM();
            console.log(this.formData);
            if (this.formData != null) {
              let data = Object.assign({}, this.formData, { dms_table2: this.arr });
              console.log(data);
              let res = addPlan(data);
            }
            this.$emit('close', false);
          })
          .catch(() => {
            // this.$notify.info({title: '提示信息',message:'已取消删除'});
          });
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
